﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShenLanCMS.Models;

namespace ShenLanCMS.Web.Controllers
{
    public class PostTypeController : Controller
    {
        private EntityContext db = new EntityContext();

        [IsAdmin]
        public ViewResult Index()
        {
            return View(db.PostTypes.ToList());
        }

        [IsAdmin]
        public ViewResult Details(int id)
        {
            PostType posttype = db.PostTypes.Find(id);
            return View(posttype);
        }

        [IsAdmin]
        public ActionResult Add()
        {
            return View();
        }

        [IsAdmin]
        [HttpPost]
        public ActionResult Add(PostType posttype)
        {
            if (ModelState.IsValid)
            {
                foreach (var item in db.PostTypes)
                {
                    if (item.TypeName == posttype.TypeName)
                    {
                        ModelState.AddModelError("TypeName", "该分类已经存在");
                        return View(posttype);
                    }
                }
                posttype.Layer = 0;
                posttype.IsLast = true;
                posttype.ParentID = 0;
                db.PostTypes.Add(posttype);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(posttype);
        }

        [IsAdmin]
        public ActionResult Edit(int id)
        {
            PostType posttype = db.PostTypes.Find(id);
            return View(posttype);
        }

        [IsAdmin]
        [HttpPost]
        public ActionResult Edit(PostType posttype)
        {
            if (ModelState.IsValid)
            {
                db.Entry(posttype).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(posttype);
        }

        //删除分类
        [IsAdmin]
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                var posts = db.Posts.Where(n => n.PostTypeID == id);
                if (posts.Count() > 0)
                    return Json("该分类正在使用中,不能删除");
                PostType posttype = db.PostTypes.Find(id);
                db.PostTypes.Remove(posttype);
                db.SaveChanges();
                return Json("删除成功");
            }
            catch { return Json("删除失败"); }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}